package com.piesat.quake.business.station.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.piesat.common.exception.BadRequestException;
import com.piesat.quake.business.device.bis.DeviceCache;
import com.piesat.quake.business.station.mapper.StationInfoMapper;
import com.piesat.quake.business.station.model.StationInfo;
import com.piesat.quake.business.station.service.RegionService;
import com.piesat.quake.business.station.service.StationInfoService;
import com.piesat.quake.business.station.service.dto.StationQueryDTO;
import com.piesat.quake.common.mqtt.decoder.entity.ReData;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import cn.hutool.poi.excel.ExcelReader;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-12-06
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class StationInfoServiceImpl extends ServiceImpl<StationInfoMapper, StationInfo> implements StationInfoService {

    @Autowired
    private StationInfoMapper stationInfoMapper;
    @Autowired
    private DeviceCache deviceCache;

    @Autowired
    @Lazy
    private RegionService regionService;

    @PostConstruct
    void init(){
        List<StationInfo> list = list();
        for (StationInfo stationInfo : list) {
            deviceCache.put(stationInfo.getId(),stationInfo);
        }
    }

    @Override
    public void saveStation(StationInfo info) {
        assert this.getById(info.getId()) != null : "站台编号已经存在";
        info.setOnline(false);
        this.save(info);
        deviceCache.put(info.getId(), info);
    }

    @Override
    @CacheEvict(cacheNames = "station", key = "#id")
    public void removeStation(String id) {
        assert this.getById(id) == null : "站台编号不存在";
        this.removeById(id);
        deviceCache.remove(id);
    }

    @Override
    @CachePut(cacheNames = "station", key = "#info.id")
    public void updateStation(StationInfo info) {
        assert this.getById(info.getId()) == null : "站台不存在";
        this.updateById(info);
        deviceCache.put(info.getId(), info);
    }

    @Override
    public List<StationInfo> findStationInfoList(String regionCode) {
        return this.lambdaQuery().eq(StationInfo::getRegionCode, regionCode).list();
    }

    @Override
    @CachePut(cacheNames = "station", key = "#info.id")
    public void unbindStation(String stationId, String regionCode) {
        this.lambdaUpdate().eq(StationInfo::getId, stationId)
                .eq(StationInfo::getRegionCode, regionCode)
                .set(StationInfo::getRegionCode, null)
                .update();
    }

    @Override
    @CachePut(cacheNames = "station", key = "#info.id")
    public void bindStation(String stationId, String regionCode) {
        StationInfo info = this.getById(stationId);
        if (info.getRegionCode() != null && info.getRegionCode().equals(regionCode)) {
            throw new BadRequestException("该站台已被绑定，请先解绑后绑定");
        }
        this.lambdaUpdate().eq(StationInfo::getId, stationId)
                .set(StationInfo::getRegionCode, regionCode)
                .update();
    }

    @Override
    public void registerStation(ReData data) {
        StationInfo stationInfo = new StationInfo();
        stationInfo.setId(data.getId());
        stationInfo.setLng(data.getLng().doubleValue());
        stationInfo.setLat(data.getLat().doubleValue());
        stationInfo.setStrain(data.getStrain().doubleValue());
        stationInfo.setAcceleration(data.getAcceleration().doubleValue());
        stationInfo.setModel(data.getModel().intValue());
        stationInfo.setVersion(data.getVersion().intValue());
        stationInfo.setOnline(true);
        this.saveOrUpdate(stationInfo);
    }

    @Override
    @Cacheable(cacheNames = "station", key = "#id")
    public StationInfo findById(String id) {
        return this.getById(id);
    }

    @Override
    public Page<StationInfo> selectByPage(StationQueryDTO dto) {

        return this.lambdaQuery().like(StationInfo::getId, dto.getBlurry())
                .or()
                .like(StationInfo::getName, dto.getBlurry())
                .page(new Page<>(dto.getPage(), dto.getSize()));
    }

    @Override
    public List<Map<String, Object>> statistic() {
//        List<Region> regionList = regionService.list();
        List<Map<String, Object>> mapList = stationInfoMapper.statistic();
//        List<String> haveRegionCodeList = mapList.stream().map(map -> (String) map.get("regionCode")).collect(Collectors.toList());
//
//        regionList.stream().forEach(region -> {
//            if (!haveRegionCodeList.contains(region.getCode())) {
//                Map<String, Object> map = new HashMap<>();
//                map.put("regionCode", region.getCode());
//                map.put("online", 0);
//                map.put("offline", 0);
//                map.put("regionName", region.getName());
//                mapList.add(map);
//            } else {
//                mapList.forEach(map -> {
//                    if (region.getCode().equals((String) map.get("regionCode"))) {
//                        map.put("regionName", region.getName());
//                    }
//                });
//            }
//        });
        return mapList;
    }

    @Override
    public List<String> getRegionCodeList() {
        return baseMapper.getRegionCodeList();
    }

    @Override
    public List<String> getDeviceIds(String regionCode){
        return baseMapper.getDeviceIds(regionCode);
    }

    @Override
    public boolean uploadExcel(MultipartFile multipartFile) {
        try {
            ExcelReader excelReader = new ExcelReader(multipartFile.getInputStream(), 0, true);
            excelReader.addHeaderAlias("站点ID", "id")
                    .addHeaderAlias("站点名称", "name")
                    .addHeaderAlias("经度", "lng")
                    .addHeaderAlias("纬度", "lat");
            List<StationInfo> list = excelReader.readAll(StationInfo.class);
            return saveBatch(list);
        } catch (IOException e) {
            return false;
        }
    }

    @Override
    public void updateDeviceTime(String id) {
        StationInfo stationInfo = baseMapper.selectById(id);
        if (stationInfo!=null) {
            StationInfo uInfo = new StationInfo();
            uInfo.setId(id);
            uInfo.setRecentlyTime(System.currentTimeMillis());
            if (stationInfo.getFirstTime()==null){
                uInfo.setFirstTime(System.currentTimeMillis());
            }
            baseMapper.updateById(uInfo);
        }
    }

    public void exportExcel(){

    }


}
